package com.easondongh.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.text.MessageFormat;
import java.util.*;

/**
 * @author donghao
 * @date 2022/9/5 21:30
 */
public class OrderTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        Map<String, Collection<Long>> shardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Set<String> actualTargetNames = new HashSet<>();
        Collection<Long> ids = shardingValuesMap.get("id");
        Collection<Long> userIds = shardingValuesMap.get("user_id");
        for (Long id : ids) {
            for (Long userId : userIds) {
                String actualTableName = MessageFormat.format("{0}_{1}_{2}", shardingValue.getLogicTableName(), (userId % 2) + 1, (id % 2) + 1);
                if(!availableTargetNames.contains(actualTableName)) {
                    throw new RuntimeException("不存在的实际表：" + actualTableName);
                }
                actualTargetNames.add(actualTableName);
            }
        }
        return new ArrayList<>(actualTargetNames);
    }

}
